package models

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"gopkg.in/ini.v1"
	"os"
)

var db *sqlx.DB

func init() {
	cfg, err := ini.Load("conf/app.ini")
	if err != nil {
		fmt.Printf("Fail to read file: %v", err)
		os.Exit(1)
	}

	user := cfg.Section("database").Key("User").String()
	password := cfg.Section("database").Key("Password").String()
	host := cfg.Section("database").Key("Host").String()
	name := cfg.Section("database").Key("Name").String()
	dataSourceName := user + ":" + password + "@tcp(" + host + ")/" + name
	database, err := sqlx.Open("mysql", dataSourceName)
	//database, err := sqlx.Open("mysql", "root:123456@tcp(127.0.0.1:6612)/go-mysql")
	if err != nil {
		fmt.Println("数据库连接错误", err)
		return
	}
	db = database
	fmt.Println("数据库连接成功", db)
}

func CloseDB() {
	defer db.Close()
}